package com.abysshal.icarte.datamodel.net;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;

import com.abysshal.icarte.datamodel.Config;
import com.abysshal.icarte.datamodel.MyLog;
import com.abysshal.icarte.datamodel.interf.MessageRecvInterf;

public class Server extends Thread{
	private int port;
	private MessageRecvInterf mri;
	private ServerSocket ss;
	private boolean running;
	
	public Server(int port, MessageRecvInterf mri){
		this.port = port;
		this.mri = mri;
		this.running = false;
		this.start();
	}
	
	@Override
	public void run() {
		try {
			ss = new ServerSocket(port);			
		} catch (IOException e) {			
			e.printStackTrace();
			return;
		}
		this.running = true;
		if (Config.VERBOSE < 4) MyLog.logd("[Server]" + "Start listening on port:" + port);
		while (true) try{
			Socket socket = ss.accept();
			if (Config.VERBOSE < 3) MyLog.logd("[Server]" + "Conn from :" + socket.getRemoteSocketAddress());
			new ClientHandler(socket, mri);
		} catch (IOException ex){
			
		} catch (Exception ex){
			ex.printStackTrace();
			if (Config.VERBOSE < 4) MyLog.logd("[Server]" + "Server error, will stop listening");
			this.running = false;
			break;
		}
	}
	
	public boolean isRunning() { return this.running;}
	
	public void close(){
		this.running = false;
		if (this.isAlive()) this.interrupt();
	}
}
